import {
  apiQueryDocumentTree, apiSaveTreeNode, apiDeleteTreeNode,
  apiQueryTableClassifier, apiQueryDocumentList, apiUploadDocument, apiSaveDocument,
  apiQueryDocumentInfo, apiQueryAllOrg, apiQueryAllUser
} from "../services/docAssetsServices";

export default {

  namespace: 'docAssets',

  state: {
    //Tree 的
    treeData: [],
    originTreeData: [],
    selectedTreeNodeId: null,

    //Tree的Modal的
    docTreeModalVisible: false,
    docTreeModalData: null,//目录节点编辑框数据
    docTreeModalLoading: false,

    //Table 的
    featureColumns: [],
    tableData: null,
    tableKeyWord: '', //当前搜索关键字，点搜索的时候修改
    tableSearchValue: '',//搜索框中内容，onChange的时候改
    selectedRowKeys: [],
    tableCurrentPage: 1,

    //文档Modal的
    docListModalVisible: false, //列表数据编辑框显示
    docListModalData: null,//列表数据编辑框数据
    transferTargetKeys: [], //弹框中Transfer的选中项
    transferTreeData: [], //Transfer组装成tree的数据
    transferUserData: []//组装前Transfer中所有用户数据，Transfer用来判断


  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    },
  },

  effects: {
    //Tree 用到的
    *queryTreeData({ payload }, { call, put, select }) { //获取Tree数据
      const response = yield call(apiQueryDocumentTree);
      console.log("获取Tree数据:",response)
      // const response = treeData
      if(response.success){
      yield put({
        type: 'changeTreeData',
        payload: {
          treeData: response.entity
        }
      })
      }
    },
    *saveTreeNode({ payload }, { call, put, select }) { //保存节点数据
      const { data } = payload
      const response = yield call(apiSaveTreeNode,data);
      console.log("保存节点结果:", response)
      // console.log("保存的data :", data)
      if(response.success){
      yield put({
        type: 'changeDocTreeModalLoading',
        payload: { docTreeModalLoading: false }
      })
      yield put({
        type: 'changeDocTreeModalVisible',
        payload: { docTreeModalVisible: false }
      })
      yield put({
        type: 'queryTreeData',
        payload: {}
      })
      }
    },
    *deleteTreeNode({ payload }, { call, put, select }) { //删除节点数据
      // const key = payload.key //跟selectedTreeNodeId应该相同
      const selectedTreeNodeId = yield select(state => state.docAssets.selectedTreeNodeId);
      const response = yield call(apiDeleteTreeNode, selectedTreeNodeId);
      console.log("删除节点结果:", response)
      if(response.success){
      yield put({
        type: 'queryTreeData',
        payload: {}
      })
      }
    },

    //Table 用到的
    *queryTableClassifier({ payload }, { call, put, select }) { //读取文档的元模型定义
      const response = yield call(apiQueryTableClassifier);
      console.log("文档元模型:", response)
      // const response = tableMetaData
      if (response.success) {
        const featureEntities = response.entity.featureEntities
        const featureColumns = parseEntitiesToColumns(featureEntities)
        yield put({
          type: 'changeFeatureColumns',
          payload: { featureColumns }
        })
      }
    },

    *queryDocumentList({ payload }, { call, put, select }) { //文档分页列表
      const selectedTreeNodeId = yield select(state => state.docAssets.selectedTreeNodeId);
      const tableKeyWord = yield select(state => state.docAssets.tableKeyWord);
      const tableCurrentPage = yield select(state => state.docAssets.tableCurrentPage);
      const params = {
        filePackageId: selectedTreeNodeId,
        page: tableCurrentPage,
        pageSize: 10,
        keyword: tableKeyWord,
      }
      const response = yield call(apiQueryDocumentList,params);
      console.log("文档列表:", response)
      console.log("请求参数:", params)

      // const response = mockTableData
      if (response.success) {
        const tableData = response.entity
        console.log("entity  table data :", tableData)
        yield put({
          type: 'changeTableData',
          payload: { tableData }
        })
        
      }
    },

    *queryDocumentInfo({ payload }, { call, put, select }) { //获取文档信息
      const docListModalData = yield select(state => state.docAssets.docListModalData);
      const response = yield call(apiQueryDocumentInfo,docListModalData.instanceId);
      console.log("获取文档信息:", response)
      // const response = docBean
      if(response.success){
        const modalData = response.entity
        const excludeUsersIds = []
        if(modalData && modalData.excludeUsersEntities){
          modalData.excludeUsersEntities.forEach(entity => {
            excludeUsersIds.push(entity.id)
          })
        }
      yield put({
        type: 'changePublishModalData',
        payload: { docListModalData: modalData }
      })
      yield put({
        type: 'changeTransferTargetKeys',
        payload: {transferTargetKeys:excludeUsersIds}
      })
    }
    },

    *queryOrgsAndUsers({ payload }, { call, put, select }) { //获取文档信息
   
      const orgResp = yield call(apiQueryAllOrg)
      const usersResp = yield call(apiQueryAllUser)

      // let transferTreeData = parseToTransfer(orgResp.entity, usersResp.entity)

      if(orgResp.success && usersResp.success){
      const transferTreeData = parseToTransfer(orgResp.entity, usersResp.entity)
      usersResp.entity.forEach(data => data.key = data.id)

      yield put({
        type: 'changeTransferUserData',
        payload: { transferUserData: usersResp.entity }
      })
      yield put({
        type: 'changeTransferTreeData',
        payload: { transferTreeData }
      })

    }
    },

    *saveDocument({ payload }, { call, put, select }) { //保存文档信息
      const fileInfo = payload.fileInfo
      const response = yield call(apiSaveDocument,fileInfo);
      console.log("保存文档信息:", response)
      if(response.success){
      yield put({
        type: 'queryDocumentList',
        payload: {}
      })
    }
    },


  },

  reducers: {
    //Tree 用到的
    changeTreeData(state, action) { //更新Tree数据，传入的接口返回数据
      const { treeData } = action.payload
      const parsedTreeData = parseTree(treeData)
      console.log("parsedTreeData",parsedTreeData,"treeData",treeData)
      return { ...state, treeData: parsedTreeData, originTreeData: treeData }
    },

    changeSelectedTreeId(state, action) { //左侧tree中选择了那行数据
      const { selectedTreeNodeId } = action.payload;
      return { ...state, selectedTreeNodeId }
    },

    //Tree的Modal用到的
    changeDocTreeModalVisible(state, action) {
      const { docTreeModalVisible } = action.payload;
      return { ...state, docTreeModalVisible }
    },
    changeDocTreeModalData(state, action) {
      const { docTreeModalData } = action.payload;
      return { ...state, docTreeModalData }
    },
    changeDocTreeModalLoading(state, action) {
      const { docTreeModalLoading } = action.payload;
      return { ...state, docTreeModalLoading }
    },


    //Table 用到的
    changeTableKeyWord(state, action) {
      const { tableKeyWord } = action.payload;
      return { ...state, tableKeyWord }
    },
    changeTableSearchValue(state, action) {
      const { tableSearchValue } = action.payload;
      return { ...state, tableSearchValue }
    },

    changeTableCurrentPage(state, action) {
      const { tableCurrentPage } = action.payload;
      return { ...state, tableCurrentPage }
    },
    changeFeatureColumns(state, action) {
      const { featureColumns } = action.payload;
      return { ...state, featureColumns }
    },
    changeTableData(state, action) {
      const { tableData } = action.payload;
      return { ...state, tableData }
    },
    changeSelectedRowKeys(state, action) {
      const { selectedRowKeys } = action.payload;
      return { ...state, selectedRowKeys }
    },


    //列表弹框用到的
    showPublishModal(state, action) {
      const { docListModalVisible } = action.payload
      return { ...state, docListModalVisible: docListModalVisible }
    },

    changePublishModalData(state, action) {
      const { docListModalData } = action.payload;
      return { ...state, docListModalData }
    },

    changeTransferTargetKeys(state, action) {
      const { transferTargetKeys } = action.payload;
      return { ...state, transferTargetKeys }
    },

    changeTransferTreeData(state, action) {
      const { transferTreeData } = action.payload;
      return { ...state, transferTreeData }
    },
    changeTransferUserData(state, action) {
      const { transferUserData } = action.payload;
      return { ...state, transferUserData }
    },

  },

};


const parseTree = (jsonArray) => {
  const nodes = []
  if (jsonArray) {
    const tmpArray = [...jsonArray]
    jsonArray.filter((value) => { return value.owner == null || value.owner.id == null })
      .forEach(element => {
        element.children = parseChildren(element, tmpArray)
        nodes.push(element)
      });
  }
  return nodes;
}

const parseChildren = (parent, jsonArray) => {
  const nodes = []
  jsonArray.filter((value) => { return (value.owner != null && value.owner.id === parent.id) })
    .forEach(element => {
      element.children = parseChildren(element, jsonArray)
      nodes.push(element)
    });
  return nodes;
}

//转换动态的表头
const parseEntitiesToColumns = (featureEntities) => {
  const featureColumns = []
  featureEntities.forEach((entity) => {
    if (entity && entity.featureColumn) {
      const combId = entity.comb ? entity.comb.combId : ''
      const enumerationItems = (entity.dataType && entity.dataType.isEnum === "T" && entity.dataType.enumeration) ? entity.dataType.enumeration.enumerationItems : null
      featureColumns.push(
        {
          id: entity.id,
          title: entity.name,
          code: entity.code,
          dataIndex: lowerAndRemoveUnderLine(entity.featureColumn.attStore),
          combId: combId,
          enumerationItems: enumerationItems
        }
      )
    }
  })
  return featureColumns
}

//字符串转小写，去掉下划线
const lowerAndRemoveUnderLine = (str) => {
  return str.toLowerCase().replace('_', '')
}

//穿梭框数据转换
const parseToTransfer = (orgs, users) => {
  const result = [...orgs]
  users.forEach(user => {
    const matchedOrg = result.find((value) => { return value.code === user.compCode })
    if (matchedOrg) {
      if (!matchedOrg.children) {
        matchedOrg.children = []
      }
      matchedOrg.children.push(user)
    }
  })
  return result
}